/**
 * Created by lsj on 2017/7/21.
 */

"use strict";

var dialogObj = {
    dialogUrl: '',
    dialogId: '',
    formId: '',
    successNote: '',
    operateType: -1,    // 0－修改 1－新增
    // 打开Dialog
    init:function (dialogId,formId) {
        dialogObj.dialogId = dialogId;
        dialogObj.formId = formId;
    },
    openDialog: function () {
        $('#'+dialogObj.dialogId).dialog('open');
    },
    openAdd: function (dialogUrl) {
        $('#'+dialogObj.dialogId).dialog({title: '新增'});
        dialogObj.operateType = 1;
        dialogObj.dialogUrl = dialogUrl;
        dialogObj.successNote = '新增成功';
        // 主要是清除combobox的自动初始化，Dialog关闭前也会调用clear方法做清除工作
        $('#'+dialogObj.formId).form('clear');
        $('#status').combobox('setValue', 1);
        dialogObj.openDialog();
    },
    // Dialog表单赋值并打开Dialog
    openUpdate: function (formData,dialogUrl) {
        if (!formData) {
            apexLayer.Error('请先选择一条记录，才能进行修改操作！');
            return;
        }
        var id = formData.id;
        if (id == null || id == '') {
            apexLayer.Error('id为空');
            return;
        }

        $('#add-dlg').dialog({title: '修改'});
        dialogObj.operateType = 0;
        dialogObj.dialogUrl = dialogUrl;
        dialogObj.successNote = '修改成功';
        for (var key in formData) {
            var $element = $('#' + key);
            if ($element.hasClass("easyui-textbox")) {
                $element.textbox('setValue', formData[key]);
            } else if ($element.hasClass("easyui-combobox")) {
                $element.combobox('setValue', formData[key]);
            } else if ($element.hasClass("easyui-slider")) {
                $element.slider('setValue', formData[key]);
            } else {
                $('#' + key).val(formData[key]);
            }
        }
        //打开弹框前，将密码进行解密.
        if ($("#userPwd").length == 1){
            var val = formData["userPwd"];
            var newVal = decryptByDES(val,"test_pwd");
            $("#userPwd").textbox('setValue', newVal);
        }

        dialogObj.openDialog();
    },
    // Dialog表单提交
    submiHandler: function (dataGridId) {
        $.messager.progress();	// display the progress bar
        $('#'+dialogObj.formId).form('submit', {
            url: dialogObj.dialogUrl,
            type:'POST',
            onSubmit: function () {
                if (!$(this).form('validate')) {
                    $.messager.progress('close');	// hide progress bar while the form is invalid
                    return false;
                }
                //提交时,将密码值进行加密
                if ($("#userPwd").length == 1){
                    var key = "test_pwd";
                    var newValue = $("#userPwd").val();
                    $("#userPwd").textbox('setValue',encryptByDES(newValue,key));
                }
                return true;
            },
            success: function (data) {
                $.messager.progress('close');	// hide progress bar while submit successfully
                var obj = JSON.parse(data);
                if (obj.code>0) {
                    apexLayer.Msg(dialogObj.successNote, 1000, function () {
                        $('#'+dataGridId).datagrid("reload");
                        $('#'+dialogObj.dialogId).dialog('close');
                    });
                } else {
                    apexLayer.Error(obj.note);
                }
            }
        });
    },
    // Dialog关闭
    cancelHandler: function () {
        $('#'+dialogObj.dialogId).dialog('close');
    },
    // Dialog重置
    reset: function () {
        // 状态还原
        dialogObj.dialogUrl = '';
        dialogObj.successNote = '';
        dialogObj.operateType = -1;
        // 清空Dialog上表单输入框原有的值
        $('#'+dialogObj.formId).form('clear'); // .form('reset')
    }
};


// 扩展easyui表单的验证
$.extend($.fn.validatebox.defaults.rules, {
    isNotBlank: {
        validator: function (value, param) {
            return $.trim(value) != '';
        },
        message: '不能为空，全空格也不行'
    },
    checkIp: {// 验证IP地址
        validator: function (value, param) {
            var reg = /^((1?\d?\d|(2([0-4]\d|5[0-5])))\.){3}(1?\d?\d|(2([0-4]\d|5[0-5])))$/;
            return reg.test(value);
        },
        message: 'IP地址格式不正确'
    },
    checkPort:{ //验证端口  0~65535之间
        validator: function (value, param) {
            if (isNaN(value)){
                return false;
            }
            if (parseInt(value,10)>65535){
                return false;
            }
            return true;
        },
        message:'端口号不正确'
    }

});

//dataGrid退出编辑状态
function saveDataGridDataExt(dg) {
    var opts = dg.datagrid('options');
    if (opts.editIndex != undefined ) {
        dg.datagrid('endEdit', opts.editIndex)
            .datagrid('acceptChanges');
        opts.editIndex = undefined;
    }
}

// 扩展easyui datagrid的方法
$.extend($.fn.datagrid.methods, {
    editCell: function (jq, param) {
        jq.each(function () {
            var fields = $(this).datagrid('getColumnFields', true).concat($(this).datagrid('getColumnFields'));
            for (var i = 0; i < fields.length; i++) {
                var col = $(this).datagrid('getColumnOption', fields[i]);
                col.editor1 = col.editor;
                if (fields[i] != param.field) {
                    col.editor = null;
                }
            }
            $(this).datagrid('beginEdit', param.index);
            var ed = $(this).datagrid('getEditor', param);
            if (ed) {
                var target;
                if ($(ed.target).hasClass('textbox-f') && ed.type!='combobox') {
                    target = $(ed.target).textbox('textbox').focus();
                } else {
                    target = $(ed.target).focus();
                }
                // 编辑单元格失去焦点触发退出编辑
                var dg = $(this);
                target.on('blur', function (event) {
                    var opts = dg.datagrid('options');
                    if (opts.editIndex != undefined ) {
                        dg.datagrid('endEdit', opts.editIndex)
                            .datagrid('acceptChanges');
                        opts.editIndex = undefined;
                    }
                });
            }
            for (var i = 0; i < fields.length; i++) {
                var col = $(this).datagrid('getColumnOption', fields[i]);
                col.editor = col.editor1;
            }

        });
    },
    enableCellEditing: function (jq) {
        return jq.each(function () {
            var dg = $(this);
            var opts = dg.datagrid('options');
            opts.oldOnClickCell = opts.onClickCell;
            opts.onClickCell = function (index, field, value) {
                if (opts.editIndex != undefined) {
                    if (dg.datagrid('validateRow', opts.editIndex)) {
                        dg.datagrid('endEdit', opts.editIndex)
                            .datagrid('acceptChanges');
                        opts.editIndex = undefined;
                    } else {
                        return;
                    }
                }
                dg.datagrid('selectRow', index).datagrid('editCell', {
                    index: index,
                    field: field
                });
                opts.editIndex = index;
                opts.oldOnClickCell.call(this, index, field, value);
            }
        });
    },
    addEditor: function (jq, param) {
        if (param instanceof Array) {
            $.each(param, function (index, item) {
                var e = $(jq).datagrid('getColumnOption', item.field);
                e.editor = item.editor;
            });
        } else {
            var e = $(jq).datagrid('getColumnOption', param.field);
            e.editor = param.editor;
        }
    },
    removeEditor: function (jq, param) {
        if (param instanceof Array) {
            $.each(param, function (index, item) {
                var e = $(jq).datagrid('getColumnOption', item);
                e.editor = {};
            });
        } else {
            var e = $(jq).datagrid('getColumnOption', param);
            e.editor = {};
        }
    },
    // 点击空白处退出编辑状态
    exitEdit: function (jq) {
        jq.parent().on('click', 'div.datagrid-body', function (event) {
            var opts = jq.datagrid('options');
            if (opts.editIndex != undefined) {
                // 退出编辑状态
                jq.datagrid('endEdit', opts.editIndex);
            }
        });
    }
});

function mysort(index, type, datagridId) {
    if ("up" == type) {
        if (index != 0) {
            var toup = $('#' + datagridId).datagrid('getData').rows[index];
            var todown = $('#' + datagridId).datagrid('getData').rows[index - 1];
            $('#' + datagridId).datagrid('getData').rows[index] = todown;
            $('#' + datagridId).datagrid('getData').rows[index - 1] = toup;
            $('#' + datagridId).datagrid('refreshRow', index);
            $('#' + datagridId).datagrid('refreshRow', index - 1);
            $('#' + datagridId).datagrid('selectRow', index - 1);
        }
    } else if ("down" == type) {
        var rows = $('#' + datagridId).datagrid('getRows').length;
        if (index != rows - 1) {
            var todown = $('#' + datagridId).datagrid('getData').rows[index];
            var toup = $('#' + datagridId).datagrid('getData').rows[index + 1];
            $('#' + datagridId).datagrid('getData').rows[index + 1] = todown;
            $('#' + datagridId).datagrid('getData').rows[index] = toup;
            $('#' + datagridId).datagrid('refreshRow', index);
            $('#' + datagridId).datagrid('refreshRow', index + 1);
            $('#' + datagridId).datagrid('selectRow', index + 1);
        }
    }

}


function appendRow(datagridId,rowJson,parentContainerId) {

    //this.$Dg.datagrid('appendRow', {});
    //this.$Dg.datagrid('appendRow', {need:"否","visible":"否","dict":"无","plugin":"无"});
    $('#' + datagridId).datagrid('appendRow', rowJson);
    //var fields = $('#' + datagridId).datagrid('getColumnFields');
    countHeight(datagridId,parentContainerId);
}

function insertRow(datagridId,rowJson,parentContainerId) {
    var row = $('#' + datagridId).datagrid('getSelected');
    if(row){
        var index = $('#' + datagridId).datagrid('getRowIndex', row);
        $('#' + datagridId).datagrid('insertRow',{
            index: index,	// index start with 0
            row: rowJson
        });

        countHeight(datagridId,parentContainerId);
    }else {
        apexLayer.Msg("未选中插入位置");
    }

}

function upRow(datagridId) {
    var row = $('#' + datagridId).datagrid('getSelected');
    var index = $('#' + datagridId).datagrid('getRowIndex', row);
    if(row){
        mysort(index, 'up', datagridId);
        $('#' + datagridId).datagrid('clearSelections');
        $('#' + datagridId).datagrid('selectRow',index-1);
        $('#' + datagridId).datagrid('uncheckRow',index);
    }else {
        apexLayer.Msg("未选中要移动的行");
    }

}

function downRow(datagridId) {
    var row = $('#' + datagridId).datagrid('getSelected');
    var index = $('#' + datagridId).datagrid('getRowIndex', row);
    if(row){
        mysort(index, 'down', datagridId);
        $('#' + datagridId).datagrid('clearSelections');
        $('#' + datagridId).datagrid('selectRow',index+1);
        $('#' + datagridId).datagrid('uncheckRow',index);
    }else {
        apexLayer.Msg("未选中要移动的行");
    }
}

function countHeight(datagridId,parentContainerId) {
    var rows = $('#' + datagridId).datagrid('getRows');
    if(rows){
        var baseHeight = 110;
        var countHeight = baseHeight+(rows.length-1)*25;
        $('#' + parentContainerId).height(countHeight+"px");
        $.parser.parse($('#' + parentContainerId));
    }
}

function deleteRow(datagridId,parentContainerId) {
    //删除多行
    var rows = $('#' + datagridId).datagrid('getSelections');
    if(rows.length>0){

        apexLayer.Confirm("确定删除所选字段内容吗？？",
            "删除字段",
            "确认",
            "取消",
            function () {
                for(var i=0; i<rows.length; i++){
                    if (rows[i]) {
                        var index = $('#' + datagridId).datagrid('getRowIndex', rows[i]);
                        $('#' + datagridId).datagrid('deleteRow', index);
                        countHeight(datagridId,parentContainerId);
                    }
                }
                apexLayer.CloseAll();
            }
        );
    }else {
        apexLayer.Msg("未选中任何行");
    }
}

/**
 * 判断运维用户是否有读写权限，开关工具栏功能按钮
 */
function toolbarSwitch() {
    if(!global_editable){
        //datagrid-新增按钮
        $("#easyuiAddBtn").linkbutton("disable");
        //datagrid-修改按钮
        $("#easyuiUptBtn").linkbutton("disable");
        //datagrid-删除按钮
        $("#easyuiDelBtn").linkbutton("disable");
        //运维人员管理页面-菜单权限修改按钮
        $("#easyuiMenuAuthBtn").linkbutton("disable");
        //统一接入用户页面-服务授权按钮
        $("#easyuiServiceAuthBtn").linkbutton("disable");
        //统一接入用户页面-参数白名单按钮
        $("#easyuiParamFilterBtn").linkbutton("disable");

    }
}
function columnSwitch(dataGridId,field) {
    if(!global_editable){
        $('#'+dataGridId).datagrid('hideColumn',field);
    }
}